/*
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-03-04 10:16:03
 * @Description  : 业务中通用的函数，渲染函数，以及转换函数
 */

import type { VNodeChild } from 'vue'
import { NEllipsis } from 'naive-ui'
import type { LogRowData } from '@/types/log'
import type { SourceRowData } from '@/types/source'
import { getIcon } from '@/constants/ua'
import { BASE_URL } from '@/constants'
import { convertToBytes } from '@/utils/index'
import SvgIcon from '@/components/SvgIcon/index.vue'
import DisableUserPic from '@/assets/images/default-avata-disable.jpg'
import defaultUserPng from '@/assets/images/userDefault.png'
import type { IndexObj } from '@/types/commom'
import { fileTypes } from '@/constants/explorer'
import type { ShareRowData } from '@/types/share'

// 数字选择器发生变化，转换为字节
export const handleNumberChange = (value: any, unit = 'GB') => {
  if (value === undefined || value === null || value === '') {
    return false
  }
  if (!/^\d+$/.test(value)) {
    return false
  }
  return convertToBytes('' + value + unit)
}

// 渲染部门label
export const renderDepLabel = (option: IndexObj): VNodeChild => {
  return [
    h(
      'div',
      {
        style: {
          display: 'flex',
          alignItems: 'center',
          fontSize: '13px'
        }
      },
      [
        h(SvgIcon, {
          icon: 'bumenwenjianjia',
          size: '16px',
          class: 'mr-[10px]'
        }),
        option.label as string
      ]
    )
  ]
}

// 渲染角色label
export const renderRoleLabel = (color: string, label: string): VNodeChild => {
  return [
    h(
      'div',
      {
        style: {
          display: 'flex',
          alignItems: 'center',
          fontSize: '13px'
        }
      },
      [
        h(SvgIcon, {
          icon: 'yuandian-copy',
          color: color,
          size: '24px'
        }),
        label as string
      ]
    )
  ]
}

// 渲染用户label
export const renderUserLabel = (option: IndexObj): VNodeChild => {
  return [
    h(
      'div',
      {
        style: {
          display: 'flex',
          alignItems: 'center',
          fontSize: '13px'
        }
      },
      [
        option.isDep
          ? h(SvgIcon, {
              icon: 'bumenwenjianjia',
              size: '16px',
              class: 'mr-1'
            })
          : h(NAvatar, {
              round: true,
              size: 16,
              color: 'rgba(0,0,0,0)',
              src: option.avator ? BASE_URL + option.avator : defaultUserPng,
              class: 'mr-1'
            }),
        option.label as string
      ]
    )
  ]
}

// 渲染排序
export const renderSort = (renderLabel: any) => {
  return h('div', { class: 'my-handle flex' }, [
    renderLabel(),
    h('div', { class: 'move' }, [
      h(SvgIcon, { icon: 'mianbaoxie-xian', color: '#1890ff' })
    ])
  ])
}

// 渲染系统配置
export const renderSystemLabel = (row: IndexObj) => {
  return row.system
    ? h(
        NTag,
        {
          style: {
            fontSize: '13px'
          },
          type: 'primary',
          bordered: false
        },
        {
          default: () => '系统配置'
        }
      )
    : ''
}

// 渲染用户头像src
export const renderAvatorSrc = (avator: string, username?: string) => {
  if (username && username === '已删除') {
    return DisableUserPic
  }
  if (!avator) {
    return defaultUserPng
  }

  return BASE_URL + avator
}

// 渲染资源创建者/修改者
export const renderSourceAvator = (source: SourceRowData) => {
  if (!source.user) {
    return DisableUserPic
  }
  if (!source.user.avator) {
    return defaultUserPng
  }

  return BASE_URL + source.user.avator
}

// 渲染用户头像
export const renderUserAvator = (avator: string, username: string) => {
  return h(
    'div',
    {
      style: {
        display: 'flex',
        alignItems: 'center',
        fontSize: '13px'
      }
    },
    [
      h(NAvatar, {
        round: true,
        size: 16,
        color: 'rgba(255,255,255,1)',
        src: renderAvatorSrc(avator, username),
        class: 'mr-1'
      }),
      `${username || ''}`
    ]
  )
}

// 渲染操作系统
export const renderOs = (os: IndexObj) => {
  if (!os.name && !os.version) {
    return '未知'
  }
  const myIcon = getIcon(os.name)
  if (myIcon) {
    return h(
      'div',
      {
        style: {
          display: 'flex',
          alignItems: 'center'
        }
      },
      [
        h(SvgIcon, { icon: myIcon, class: 'mr-1', size: '14px' }),
        os.name + ' ' + os.version
      ]
    )
  } else {
    return os.name + ' ' + os.version
  }
}

// 渲染IP
export const renderIp = (ip: string) => {
  try {
    const matchs = ip.match(/\d+.\d+.\d+.\d+/)
    return matchs![0]
  } catch {
    return '未知'
  }
}

// 渲染日志导出时格式化字符串
export const renderLogExport = (log: LogRowData) => {
  log.userInfo = ''
  if (log.userId) {
    log.userInfo += 'userId:' + log.userId
  }

  if (log.username) {
    log.userInfo += '    username:' + log.username
  }

  const parseUa = (os: IndexObj) => {
    if (!os.name && !os.version) {
      return '未知'
    } else {
      return os.name + ' ' + os.version
    }
  }

  log.browser = parseUa(log.uaParse.browser)
  log.os = parseUa(log.uaParse.os)
}

// 渲染分享导出时格式化字符串
export const renderShareExport = (log: ShareRowData) => {
  log.userInfo = ''
  if (log.User) {
    log.userInfo += 'userId:' + log.User.id
    log.userInfo += '    username:' + log.User.username
  }
}

// 选择选中的tag
export const renderTag: any = (
  option: IndexObj,
  handleClose: any,
  renderLabel: any
) => {
  return h(
    NTag,
    {
      style: {
        padding: '0 3px 0 3px'
      },
      size: 'small',
      round: true,
      closable: true,
      onClose: (e: MouseEvent) => {
        e.stopPropagation()
        handleClose()
      }
    },
    {
      default: () => renderLabel()
    }
  )
}

// 渲染下拉菜单
export const renderDropLabel = (
  icon: string,
  label: string,
  color?: string,
  iconSize?: string,
  iconColor?: string
): VNodeChild => {
  return [
    h(
      'div',
      {
        style: {
          display: 'flex',
          alignItems: 'center',
          fontSize: '13px',
          color: color || 'rgb(51, 54, 57)'
        }
      },
      [
        h(SvgIcon, {
          icon: icon,
          size: iconSize || '18px',
          color: iconColor || 'rgb(51, 54, 57)',
          class: 'mr-2'
        }),
        h(
          NEllipsis,
          {
            style: {
              'max-width': '100px'
            },
            tooltip: {
              raw: true,
              'content-class': 'bg-yellow-100 text-[#000] p-2',
              'arrow-class': '!bg-yellow-100'
            }
          },
          { default: () => label as string }
        )
      ]
    )
  ]
}

// 渲染选择器
export const renderSelect = (option: any) => {
  return h(
    'div',
    {
      style: {
        fontSize: '13px'
      }
    },
    option.label
  )
}

// 根据文件后缀名获取文件类型
export const getFileTypeBySuffix = (filename: string) => {
  const suffix = filename.slice(((filename.lastIndexOf('.') - 1) >>> 0) + 2)

  const res = fileTypes.find((item) => {
    return item.suffix.includes(suffix)
  })

  if (!res) {
    return {
      type: 1,
      name: '普通文件',
      myIcon: 'wenjianleixing-biaozhuntu-weizhiwenjian',
      suffix: []
    }
  }

  return res
}

// 根据文件类型获取文件类型详情
export const getFileTypeInfoByType = (type: number) => {
  let fileType = fileTypes.find((item) => item.type === type)
  if (!fileType) {
    fileType = fileTypes[1]
  }
  return fileType
}

// 渲染文件类型
export const renderFileType = (type: number) => {
  let fileType = fileTypes.find((item) => item.type === type)
  if (!fileType) {
    fileType = fileTypes[1]
  }
  return fileType.name
}

// 渲染面包屑
export const renderBread = (key: string, label: string) => {}

// 下载文件
export const downLoadFile = (url: unknown, fileName: string) => {
  const blob = new Blob([url as string], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
  })
  if ('download' in document.createElement('a')) {
    // 非IE下载
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = window.URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href) // 释放URL对象
    document.body.removeChild(elink)
  } else {
    // IE10+ 下载
    ;(navigator as any).MsSaveBlob(blob, fileName)
  }
}

// 页面全屏
export const fullScreen = () => {
  // 全屏
  const element = document.documentElement as any
  if (element.requestFullscreen) {
    element.requestFullscreen()
  } else if (element.mozRequestFullScreen) {
    /* Firefox */
    element.mozRequestFullScreen()
  } else if (element.webkitRequestFullscreen) {
    /* Chrome, Safari and Opera */
    element.webkitRequestFullscreen()
  } else if (element.msRequestFullscreen) {
    /* IE/Edge */
    element.msRequestFullscreen()
  }
}

// 导出一个通用的编辑组件
// 定义一个可编辑的表单列组件
export const ShowOrEdit = defineComponent({
  props: {
    value: [String, Number],
    onUpdateValue: [Function, Array],
    isEdit: [Boolean],
    onEditChange: [Function, Array],
    onFinish: [Function, Array]
  },
  setup(props: any) {
    watch(
      () => props.isEdit,
      (newValue) => {
        if (newValue) {
          nextTick(() => {
            inputRef.value!.focus()
            // inputRef.value!.select()
          })
        }
      },
      {
        immediate: true
      }
    )
    // const isEdit = ref(false)
    const inputRef = ref<any>(null)
    const inputValue = ref(props.value)
    const initValue = ref(props.value)
    function handleOnClick(e: MouseEvent) {
      e.stopPropagation()
      props.onEditChange(true)
      if (props.isEdit) {
        nextTick(() => {
          inputRef.value!.focus()
          // inputRef.value!.select()
        })
      }
    }
    function handleChange() {
      props.onUpdateValue(inputValue.value)
      props.onEditChange(false)
    }

    function handleBlur() {
      props.onUpdateValue(inputValue.value)
      props.onEditChange(false)
      props.onFinish(initValue.value)
    }
    return () =>
      h(
        'div',
        {
          style: 'min-height: 22px',
          onClick: handleOnClick,
          ondragstart(e: MouseEvent) {
            e.stopPropagation()
          }
        },
        props.isEdit
          ? h(NInput, {
              ref: inputRef,
              value: inputValue.value as any,
              onUpdateValue: (v: any) => {
                inputValue.value = v
              },
              onChange: handleChange,
              onBlur: handleBlur,
              onKeydown(e: KeyboardEvent) {
                if (e.key === 'Enter') {
                  handleChange()
                }
              }
            })
          : h(
              NEllipsis,
              {
                style: {
                  'max-width': '100px'
                },
                tooltip: {
                  raw: true,
                  'content-class': 'bg-yellow-100 text-[#000] p-2',
                  'arrow-class': '!bg-yellow-100'
                }
              },
              { default: () => props.value }
            )
      )
  }
})
